<template>
    <div class="comment-item">
        <div class="comment-user-avatar">
            <img class="user-avatar" :src="comment.icon || config.defaultImg" alt="">
        </div>
        <div class="comment-info">
            <div class="comment-user-name">
                <span>{{ comment.userName }}</span>
            </div>
            <div class="comment-content" @click="triggerActionSheet">
                <CommentEntity
                    :comment="comment"
                    :level="level"
                    :sourceShow="sourceShow"
                    @on-time-slice="handleTimeSlicePlay"
                    @on-source="(itemId)=>{emit('on-source', itemId)}"
                />
            </div>

            <div class="comment-extra">
                <div class="comment-time">
                    <span>{{ dealDynamicTime(comment.gmtCreate) }}</span>
                </div>
                <!-- <div class="comment-user-actions">
                    <template v-if="level === 1">
                        <div class="action-replay" @click="onReply">
                            <i class="icon"></i>
                        </div>
                    </template>
                    <div class="action-like" :class="{'is--liked': liked}" @click="onLike">
                        <i class="icon"></i>
                        <span class="count">{{ likeCount > 99 ? '99+' : likeCount }}</span>
                    </div>
                </div> -->
            </div>

            <template v-if="level === 1 && page.total">
                <div class="reply-list">
                    <comment
                        v-for="reply in replies"
                        :key="reply.id"
                        :comment="reply"
                        :level="2"
                        :create-user-id="createUserId"
                        @refresh-replies="onRefreshReplies"
                    />
                </div>
                <div class="reply-more" @click.stop="handleReplyExpand">
                    <template v-if="replyCount">
                        <span class="expand-arrow">展开 {{ replyCount }} 条回复</span>
                        <img src="~@/assets/images/comment/more-down-icon.png" alt="" width="10">
                    </template>
                    <template v-else>
                        <span class="expand-arrow">收起</span>
                        <img src="~@/assets/images/comment/more-up-icon.png" alt="" width="10">
                    </template>
                </div>
            </template>
        </div>

        <van-action-sheet
            v-model:show="actionSheetVisible"
            :actions="actions"
            :description="description"
            cancel-text="取消"
            @select="onActionSelected"
            @cancel="setActionSheetVisible(false)"
            teleport="body"
            safe-area-inset-bottom
        />
    </div>
</template>

<script setup>
import CommentEntity from './comment-entity';
import {computed, reactive, ref} from 'vue';
import {useRoute} from 'vue-router';
import {useStore} from 'vuex';
import {dealDynamicTime} from '@/lib/tools'
import { queryToJson } from '@/lib/tools';
import config from '@/global/config';

const route = useRoute();
const store = useStore();

const props = defineProps({
    isCreater: {
        type: Boolean,
        default: false
    },
    comment: {
        type: Object,
        default: () => {}
    },
    level: {
        type: [Number, String],
        default: 1
    },
    sourceShow: {
        type: Boolean,
        default: false
    },
    catalogueId: {
        type: [String, Number],
        default: ''
    }
});
const emit = defineEmits(['reply', 'refresh-replies', 'refresh-comments', 'play-to-specified-point', 'on-source']);

const currentUser = computed(() => {
    return store.state?.currentUser || {};
});

const replies = ref([]);
const replyCount = ref(props.comment.replyCount);
const page = reactive({
    pageIndex: 1,
    pageSize: 5,
    total: props.comment.replyCount
})
function handleReplyExpand() {
    if (replyCount.value === 0) {
        replyCount.value = page.total;
        page.pageIndex = 1;
        replies.value = [];
    } else {
        if (replies.value.length) {
            page.pageIndex++;
            queryReplyList();
        } else {
            page.pageIndex = 1;
            queryReplyList();
        }
    }
}

function queryReplyList() {
    let catalogueId = props.catalogueId || route.query.catalogueId || '';
    if (!route.params?.moocId || !catalogueId) {
        return false;
    }
    G_transmit('commentListByCatalogue', {
        queries: {
            bizId: catalogueId, // 课件id
            bizSource: 'mooc', // 主体来源
            commentLevel: 1, // 层级(1:一级评论, 2:二级评论 n:n级评论）
            pageIndex: page.pageIndex, // 第几页
            pageSize: page.pageSize, // 页面大小 （只有在pageSize=20 的条件下才能使用缓存）
            parentSource: route.params.moocId, // 慕课id
            parentCommentId: 0, // # 父级评论ID 一级评论传0

        }
    }).then(({data}) => {
        if (page.pageIndex === 1) {
            replies.value = data.rows || [];
        } else {
            replies.value = replies.value.concat(data.rows || []);
        }
        page.total = data.total;
        replyCount.value = page.total - replies.value.length;
        if (replyCount.value < 0) {
            replyCount.value = 0;
        }
    })
}

/* 回复 */
function onReply() {
    emit('reply', props.comment, onReplied);
}
const onReplied = () => {
    page.total++;
    if (replies.value.length) {
        onRefreshReplies();
    } else {
        replyCount.value++;
    }
};
const onRefreshReplies = (val) => {
    page.pageIndex = 1;
    queryReplyList();
};

/* 点赞 */
const likeCount = ref(props.comment.likeCount);
const liked = ref(props.comment.liked);
function onLike() {
    const action = liked.value
        ? { liked: 0, text: '取消点赞', portalName: 'userCancelLike' }
        : { liked: 1, text: '点赞', portalName: 'userAddLike' };

    G_transmit(action.portalName, {
        data: {
            bizId: props.comment.id,
            bizSource: 'comment'
        }
    }).then(() => {
        liked.value ? likeCount.value-- : likeCount.value++;
        liked.value = !liked.value;
        G_dispatchEvent('toast', { message: action.text + '成功', type: 'success'});
    })
}

const actions = ref([]);
const description = ref('');
const actionSheetVisible = ref(false);
function setActionSheetVisible(visible) {
    actionSheetVisible.value = visible;
}

function triggerActionSheet() {
    const arr = [];
    // if (props.level === 1) {
    //     arr.push({ name: `回复${props.comment.createUserName}`, value: 1 });
    // }
    if (props.isCreater || props.comment.userId === currentUser.value.userId) {
        arr.push({ name: '删除评论', color: '#171A1D', value: 2});
    }
    description.value = '';
    if (arr.length) {
        actions.value = arr;
        setActionSheetVisible(true);
    }
}
function onActionSelected(action) {
    switch (action.value) {
        // 回复
        case 1:
            emit('reply', props.comment, onReplied);
            setActionSheetVisible(false);
            break;
        // 删除确认
        case 2:
            setActionSheetVisible(false);
            setTimeout(() => {
                if (props.level === 1) {
                    if (page.total) {
                        description.value = '删除评论后，评论下的所有回复都会被删除';
                    } else {
                        description.value = '确定删除评论吗？';
                    }
                }
                if (props.level === 2) {
                    description.value = '确定删除回复吗？';
                }
                actions.value = [{ name: '删除评论', color: '#FF4719', value: 3 }];
                setActionSheetVisible(true);
            }, 300);
            break;
        // 删除
        case 3:
            deleteComment();
            break;
    }
}

function deleteComment() {
    G_transmit('deleteCatalogueComment', {
        data: {
            id: props.comment.id,
        }
    }).then(() => {
        G_dispatchEvent('toast', { message: '删除成功', type: 'success'});
        if (props.level === 2) {
            emit('refresh-replies');
        } else {
            emit('refresh-comments');
        }
    })
}

function handleTimeSlicePlay(data) {
    emit('play-to-specified-point', data);
}
</script>

<style lang="scss" scoped>
.comment-item {
    padding: 0 15px;
    display: flex;
    align-items: flex-start;

    .comment-user-avatar {
        flex: none;
        margin-right: 8px;
        padding-top: 15px;

        .user-avatar {
            height: 34px;
            width: 34px;
            border-radius: 50%;
            overflow: hidden;
            object-fit: cover;
        }
    }
    .comment-info {
        flex: 1;
        padding: 15px 0;
        line-height: 22px;
        font-size: 14px;
        color: #171A1D;
        border-bottom: 1px solid #EEE;

        .comment-user-name {
            color: #6E7074;
        }
        .comment-content {
            margin-top: 4px;
        }

        .comment-extra {
            margin-top: 8px;
            display: flex;
            justify-content: space-between;
            align-items: center;

            .comment-time {
                font-size: 13px;
                color: #A2A3A4;
            }
            .comment-user-actions {
                display: flex;
                align-items: center;

                .action-replay,
                .action-like {
                    margin-left: 20px;
                    display: flex;
                }

                .icon {
                    display: block;
                    height: 16px;
                    width: 16px;
                    margin: 2px;
                    background-position: center center;
                    background-repeat: no-repeat;
                    background-size: contain;
                }
                .action-replay {
                    .icon {
                        background-image: url(~@/assets/images/comment/comment-icon.png);
                    }
                }
                .action-like {
                    .count {
                        margin-left: 4px;
                        color: #A2A3A4;
                    }
                    .icon {
                        background-image: url(~@/assets/images/comment/like-icon.png);
                    }

                    &.is--liked {
                        .icon {
                            background-image: url(~@/assets/images/comment/liked-icon.png);
                        }
                    }
                }
            }
        }

        .reply-list {
            .comment-item {
                padding: 0;
            }
            .comment-info {
                padding: 15px 0 0;
                border: none;
            }
        }
        .reply-more {
            background: #F5F5F5;
            border-radius: 13px;
            margin-top: 10px;
            padding: 2px 12px;
            display: inline-flex;
            justify-content: center;
            align-items: center;
            color: #6E7074;

            img {
                margin-left: 4px;
                vertical-align: middle;
            }
        }
    }
}
</style>